<template>
  <div>

    <div class="search-container">
      <el-button icon="el-icon-zoom-out"  @click="resetDateFilter" type="info" plain>取消日期筛选器</el-button>
      <el-button icon="el-icon-zoom-out" @click="clearFilter" type="info" plain>取消选择筛选器</el-button>
      <el-button icon="el-icon-zoom-out" @click="toggleSelection()" type="info" plain>取消选择</el-button>

      <!-- Form -->
      <el-button icon="el-icon-circle-plus-outline"  @click="dialogFormVisible = true" type="success" >添加</el-button>
      <span class="space" style="display: inline-block; width: 10px;"></span>
      <el-select v-model="select" clearable placeholder="请选择" @change="handleSelectChange" class="select-box">
        <el-option label="档案号" value="1"></el-option> <!-- 档案号选项 -->
        <el-option label="电话号" value="2"></el-option> <!-- 电话号选项 -->
        <el-option label="预约日期" value="3"></el-option> <!-- 预约日期选项 -->
      </el-select>

      <div class="date-picker-container" v-if="showDatePicker && select === '3'"> <!-- 如果选择的是预约日期且选择框非空，则显示日期选择器和搜索按钮 -->
        <el-date-picker v-model="dateValue" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions" @change="handleDateChange"></el-date-picker> <!-- 日期选择器，增加了 @change 事件监听 -->
      </div>

      <div class="input-container" v-else-if="select !== ''"> <!-- 如果选择的不是预约日期且选择框非空，则显示输入框和搜索按钮 -->
        <el-input v-model="inputValue" :placeholder="inputPlaceholder" class="input-with-select" @input="handleSelectChange"></el-input> <!-- 输入框 -->
      </div>

      <div class="disabled-input-container" v-else> <!-- 如果选择框为空，则显示禁用的输入框 -->
        <el-input v-model="inputValue" :placeholder="disabledInputPlaceholder" class="input-with-select" disabled></el-input> <!-- 禁用的输入框 -->
      </div>

      <el-button icon="el-icon-search" @click="handleSearch" :disabled="disableSearchButton"></el-button> <!-- 搜索按钮 -->
    </div>
    <el-dialog title="添加预约信息" :visible.sync="dialogFormVisible" :before-close="clearForm">

      <el-button type="success" icon="el-icon-first-aid-kit" @click="cxtcff">选择套餐</el-button>

      <el-dialog :custom-class="'blue-dialog'" title="选择套餐" :visible.sync="dialogTableVisible" :before-close="handleClose" append-to-body>
        <div class="search-container">


          <div class="disabled-input-container" >
            <el-input clearable v-model="tcinputValue" :placeholder="tcdisabledInputPlaceholder" class="input-with-select" ></el-input> <!-- 套餐搜索输入框 -->

          </div>
          <span class="space" style="display: inline-block; width: 10px;"></span>


          <div class="disabled-input-container" >

            <!-- 这是一个单选按钮组 -->
            <el-radio-group v-model="tcradio" :key="radioKey">
              <!-- 男性选项 -->
              <el-radio label="男" @click.native.prevent="changeRadio('男')">男</el-radio>
              <!-- 女性选项 -->
              <el-radio label="女" @click.native.prevent="changeRadio('女')">女</el-radio>
            </el-radio-group>
          </div>

          <span class="space" style="display: inline-block; width: 10px;"></span>

          <el-button icon="el-icon-search" @click="tchandleSearch" :disabled="disableSearchButton"></el-button> <!-- 搜索按钮 -->
        </div>
        <el-table
          :data="gridData.slice((tccurrentPage-1)*tcpageSize,tccurrentPage*tcpageSize)"
          ref="singleTable"
          @row-click="setCurrent"
          highlight-current-row>
          <el-table-column property="name" label="套餐名称" width="150"></el-table-column>
          <el-table-column property="sex" label="使用人群" width="200"></el-table-column>
          <el-table-column property="remark" label="套餐介绍"></el-table-column>
        </el-table>
        <div class="wrapper">
          <div class="block">
            <el-pagination
              @size-change="tchandleSizeChange"
              @current-change="tchandleCurrentChange"
              :current-page.sync="tccurrentPage"
              :page-size="tcpageSize"
              layout="prev, pager, next, jumper"
              :total="gridData.length">
            </el-pagination>
          </div>
        </div>

        <div slot="footer" class="dialog-footer">
          <el-button type="danger" @click="handleClose">退 出</el-button>
          <el-button type="primary" @click="save">保 存</el-button>
        </div>
      </el-dialog>

      <el-form :model="form">
        <el-form-item label="检查套餐" :label-width="formLabelWidth">
          <el-input :disabled="true" v-model="form.package" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="姓名" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="身份证" :label-width="formLabelWidth">
          <el-input v-model="form.idcard" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="出生日期" :label-width="formLabelWidth">
            <el-date-picker
              v-model="form.date1"
              type="date"
              placeholder="选择日期">
            </el-date-picker>
        </el-form-item>
        <el-form-item label="手机号" :label-width="formLabelWidth">
          <el-input v-model="form.number" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别" :label-width="formLabelWidth">
          <el-radio v-model="form.radio" label="1">男</el-radio>
          <el-radio v-model="form.radio" label="2">女</el-radio>
        </el-form-item>
        <el-form-item label="年龄" :label-width="formLabelWidth">
          <el-input v-model="form.age" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="婚姻状态" :label-width="formLabelWidth">
          <el-input v-model="form.marital" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="预约时间" :label-width="formLabelWidth">
          <el-date-picker
            v-model="form.date2"
            align="right"
            type="date"
            placeholder="选择日期"
            :picker-options="tjpickerOptions">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="clearForm">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>

      </div>
    </el-dialog>
  <el-table
    :data="tableData.slice((currentPage-1)*pageSize,currentPage*pageSize)"
    ref="filterTable"
    height="630"
    style="width: 100%">
    <el-table-column
      type="selection"
      width="55">
    </el-table-column>
    <el-table-column
      prop="orderDate"
      ref="dateColumn"
      label="预约日期"
      :sort-method="sortHandler"
      sortable
      width="180"
      column-key="date"
      :filters="[{text: '2023-09-20', value: '2023-09-20'}, {text: '2023-09-21', value: '2023-09-21'}, {text: '2023-09-22', value: '2023-09-22'}, {text: '2023-09-23', value: '2023-09-23'}]"
      :filter-method="filterHandler"
    >
    </el-table-column>
    <el-table-column
      label="档案号"
      prop="id">
    </el-table-column>
    <el-table-column
      label="姓名"
      prop="name">
    </el-table-column>

    <el-table-column
      label="手机号码"
      prop="phoneNumber">
    </el-table-column>

    <el-table-column
      prop="orderType"
      label="预约类型"
      width="100"
      :filters="[{ text: '电话预约', value: '电话预约' }, { text: '微信预约', value: '微信预约' }]"
      :filter-method="filterTag"
      filter-placement="bottom-end">
      <template slot-scope="scope">
        <el-tag
          :type="scope.row.orderType === '电话预约' ? 'primary' : 'success'"
          disable-transitions>{{scope.row.orderType}}</el-tag>
      </template>
    </el-table-column>

    <el-table-column
      label="预约状态"
      prop="orderStatus">
    </el-table-column>

    <el-table-column label="操作" >

      <template slot-scope="scope">
        <el-popover
          placement="top-start"
          title="确认预约"
          width="200"
          trigger="hover"
          content="确认预约……">
          <el-button
            size="mini"
            type="text"
            slot="reference"
            @click="confirmappointment(scope.$index, scope.row)">确认预约
          </el-button>
        </el-popover>



        <el-popconfirm

            confirm-button-text='确认'
            cancel-button-text='取消'
            icon="el-icon-warning-outline"
            icon-color="red"
            title="你确定要取消预约吗？"
            @onConfirm="cancelreservation(scope.$index, scope.row)"
        >

          <el-button
              size="mini"
              type="text"
              slot="reference">取消预约
          </el-button>


        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
    <div class="wrapper">
      <div class="block">
        <el-pagination
          @size-change="yyhandleSizeChange"
          @current-change="yyhandleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.length">
        </el-pagination>

      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
export default {

  beforeCreate() {
    console.log('beforeCreate: 页面加载前执行方法')
    axios.get('api/order/findAll').then(res => {
      console.log(res)
      this.tableData1=res.data.data;
      this.tableData = res.data.data
      console.log(this.tableData.length)
    })
  },
  data() {

    return {
      pageSize:10,//预约每页最大显示条数
      currentPage:1,//预约当前页数
      tableData: [],//预约显示集
      tableData1: [],//预约结果集
      gridData: [],//套餐显示集
      gridData1: [],//套餐结果集
      yysearch: '',//预约搜索条件
      tcsearch: '',//套餐搜索条件
      dialogTableVisible: false,//套餐信息页面
      dialogFormVisible: false,//添加页面
      formLabelWidth: '120px',//from表单控件长度
      tccurrentPage: 1,//套餐分页当前页数
      tcpageSize:4,//套餐每页最大显示条数
      currentPage4: 2,//预约分页当前页数
      currentRow: null,//取消选中套餐变量
      input3: '',
      select: '', // 搜索选择的选项
      showDatePicker: false, // 是否显示日期选择器
      inputValue: '', // 预约搜索输入框的值
      tcinputValue:'',//套餐搜索输入框的值
      dateValue: '', // 日期选择器的值
      disableSearchButton: false, // 是否禁用搜索按钮
      tcradio: '',//套餐搜索性别条件
      radioKey: false,// 单选按钮组的唯一标识符

      form: {
        packageid: '',//套餐编号
        package: '',//套餐
        name: '',//姓名
        idcard: '',//身份证
        number: '',//号码
        radio: '',//性别
        age:'',//年龄
        marital:'',//婚姻状态
        date1: '',//出生日期
        date2: '',//预约日期
        ordertype: '微信预约'//预约类型
      },
      pickerOptions: {// 日期选择器的选项
        disabledDate(time) {
          const now = new Date(); // 创建当前时间的日期对象
          now.setHours(0, 0, 0, 0); // 设置时间为当天的零点时间
          return time.getTime() < now.getTime();//今天之前的日期无法选择

        },
        shortcuts: [{
            text: '后一周',
            onClick(picker) { // 后一周的快捷选项
              const start = new Date();
              const end = new Date();
              end.setTime(end.getTime() + 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]); // 使用 picker.$emit 触发自定义事件
            },
          },
          {
            text: '后一个月',
            onClick(picker) { // 后一个月的快捷选项
              const start = new Date();
              const end = new Date();
              end.setTime(end.getTime() + 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]); // 使用 picker.$emit 触发自定义事件
            },
          },
          {
            text: '后三个月',
            onClick(picker) { // 后三个月的快捷选项
              const start = new Date();
              const end = new Date();
              end.setTime(end.getTime() + 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]); // 使用 picker.$emit 触发自定义事件
            },
          }]
      },
      tjpickerOptions: {
        disabledDate(time) {
          const now = new Date(); // 创建当前时间的日期对象
          now.setHours(0, 0, 0, 0); // 设置时间为当天的零点时间
          return time.getTime() < now.getTime();//今天之前的日期无法选择
        },
        shortcuts: [
          {
            text: '明天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24);
              picker.$emit('pick', date);
            },
          },
          {
            text: '后天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 2);
              picker.$emit('pick', date);
            },
          },
          {
            text: '一周后',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            },
          },
        ],
      }

    }
  },
  computed: {
    inputPlaceholder() { // 输入框的提示文本根据选择框的值动态改变

      console.log(`当前下拉框选中的值`+this.select);

      if (this.select === '1') {
        return '请输入档案号搜索';
      } else if (this.select === '2') {
        return '请输入电话号搜索';
      } else {
        return '请输入内容';
      }
    },
    disabledInputPlaceholder() { // 禁用输入框的提示文本根据选择框的值动态改变
      if (this.select === '1') {
        return '请输入档案号搜索';
      } else if (this.select === '2') {
        return '请输入电话号搜索';
      } else {
        return '搜索所有';
      }
    },
    tcdisabledInputPlaceholder() { // 禁用输入框的提示文本根据选择框的值动态改变

        return '检测套餐';

    },
  },
  methods: {

    changeRadio(val) {// 切换选择的值
      this.tcradio = this.tcradio == val ? '' : val

      this.radioKey = !this.radioKey// 切换唯一标识符
    },
    resetDateFilter() {//取消选择日期筛选器
      this.$refs.filterTable.clearFilter('date');
    },
    clearFilter() {//取消选择筛选器
      this.$refs.filterTable.clearFilter();
    },
    cxtcff() {//取消选择筛选器

      axios.get('api/order/tcfindAll').then(res => {
        console.log(res.data.data)
        this.gridData1=res.data.data;
        this.gridData = res.data.data
        console.log(this.gridData.length)
      })
      this.dialogTableVisible = true;
    },
    formatter(row, column) {
      return row.number;
    },
    filterTag(value, row) {//预约类型筛选器
      console.log(`是否进入预约类型筛选器`);

      return row.orderType === value;

    },
    toggleSelection(rows) {//取消选择预约复选框
      if (rows) {
        rows.forEach(row => {
          this.$refs.filterTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.filterTable.clearSelection();
      }
    },
    filterHandler(value, row, column) {//日期筛选器
      const property = column['property'];
      console.log(`property:`+property);
      console.log(`row[property]:`+row[property]);
      return row[property] === value;
    },
    sortHandler(order) {

        console.log('执行排序操作');

    },
    sortHandler2(order) {

      const sortedData = [...this.tableData]; // 创建 tableData 的副本

      sortedData.sort((a, b) => {
        if (order === 'ascending') {
          return new Date(a.orderDate) - new Date(b.orderDate);
        } else if (order === 'descending') {
          return new Date(b.orderDate) - new Date(a.orderDate);
        }
        return 0;
      });
      // 在这里使用排序后的 sortedData 数组
      console.log(sortedData);
    },
    tchandleSizeChange(val) {//预约每页显示页数改变时调用
      console.log(`每页 ${val} 条`);
    },
    tchandleCurrentChange(val) {//预约每页显示页数改变时调用
      console.log(`每页 ${val} 条`);
    },
    yyhandleSizeChange(val) {//预约每页显示页数改变时调用
      this.pageSize=val;
      console.log(`每页 ${val} 条`);
    },
    yyhandleCurrentChange(val) {// 预约当前页码改变时调用
      this.currentPage=val;
      console.log(`当前页: ${val}`);
    },

    confirmappointment(index, row) {//确认预约
      console.log('是否进入确认预约');

      console.log('预约编号'+row.id);
      axios.post('api/order/xgyyzt', {
        id: row.id,
        orderstatus:'确认预约'
      }).then(res => {
        console.log(res.data.data);
        alert(res.data.data);
      });
      this.cxsyyyxx();
      console.log("666")

    },
    cancelreservation(index, row) {//取消预约
      console.log('是否进入取消预约');

      console.log('预约编号'+row.id);
      axios.post('api/order/xgyyzt', {
        id: row.id,
        orderstatus:'取消预约'
      }).then(res => {
        console.log(res.data.data);
        alert(res.data.data);
      });
      this.cxsyyyxx();
    },
    setCurrent(row) {//取消选择套餐
      if (this.currentRow === row) {
        this.$refs.singleTable.setCurrentRow();
        this.currentRow = null;
      } else {
        this.$refs.singleTable.setCurrentRow(row);
        this.currentRow = row;
      }
    },
    save() {//保存选中的套餐
      if (this.currentRow) {
        console.log("当前选中行的名称：", this.currentRow.name);
        this.dialogTableVisible = false;
        this.form.package = this.currentRow.name; // 将当前选中行的名称赋给 form.package
        this.form.packageid=this.currentRow.id;
        this.$message({
          message: '选择成功',
          type: 'success'
        });
      } else {
        this.$message({
          message: '未选中任何行',
          type: 'error'
        });

      }
      console.log("套餐编号"+this.form.packageid);
      // 在这里取消选中状态
      this.$refs.singleTable.setCurrentRow();
      this.dialogTableVisible = false
    },
    handleClose() {

      this.$confirm('是否退出选择套餐?', '确认信息', {
        distinguishCancelAndClose: true,
        confirmButtonText: '取消',
        cancelButtonText: '退出'
      })
        .then(() => {
          this.$message({
            type: 'info',
            message: '放弃退出,继续选择'
          });
        })
        .catch(action => {
          this.$message({
            type: 'info',
            message: action === 'cancel'
              ? '放弃选择并离开页面'
              : '停留在当前页面'
          })
          if(action!=='close') {
            // 在这里取消选中状态
            this.$refs.singleTable.setCurrentRow();
            this.dialogTableVisible = false
          }
        });


    },
    clearForm() {


      this.$confirm('是否退出添加?', '确认信息', {
        distinguishCancelAndClose: true,
        confirmButtonText: '取消',
        cancelButtonText: '退出'
      })
        .then(() => {
          this.$message({
            type: 'info',
            message: '放弃退出,继续添加'
          });
        })
        .catch(action => {
          this.$message({
            type: 'info',
            message: action === 'cancel'
              ? '放弃添加并离开页面'
              : '停留在当前页面'
          })
          if(action!=='close') {
            for (const key in this.form) {
              this.form[key] = '';
            }
            this.dialogFormVisible = false

          }
        });
    },
    submitForm() {
      console.log(this.form);
      axios.post('api/order/tjyy',this.form).then(res => {
        console.log(res.data.data)
        //alert(res.data.data);
        this.$message({
          message: res.data.data,
          type: 'success'
        });
      })
      this.cxsyyyxx();
      for (const key in this.form) {
        this.form[key] = '';
      }
      this.dialogFormVisible = false

    },
    handleSelectChange() { // 选择框或输入框的值变化事件
      if (this.select === '3') { // 如果选择的是预约日期
        this.showDatePicker = true; // 显示日期选择器
        this.disableSearchButton = this.dateValue === '' || this.dateValue === null; // 日期选择器没有值时禁用搜索按钮
      } else { // 如果选择的是其他选项
        this.showDatePicker = false; // 隐藏日期选择器
        if (this.select === '1' || this.select === '2') { // 如果选择的是档案号或电话号
          this.disableSearchButton = this.inputValue.trim() === ''; // 输入框没有值时禁用搜索按钮
        } else {
          this.disableSearchButton = false; // 不禁用搜索按钮
          this.inputValue = ''; // 清空输入框的值
          this.dateValue = ''; // 清空日期选择器的值
        }
      }
    },
    handleDateChange() { // 日期选择器变化事件
      this.disableSearchButton = this.dateValue === '' || this.dateValue === null; // 日期选择器没有值时禁用搜索按钮
    },
    handleSearch() { // 搜索按钮点击事件
      let param = '';
      this.tableData=this.tableData1;
      console.log("ss"+this.select); // 输出搜索参数
      let listtable=[];
      if (this.select === '1') { // 如果选择的是档案号
        param = `按档案号"${this.inputValue}"搜索`;
        if(this.inputValue){
          this.tableData.filter((item)=>{
            if(item.id===parseInt(this.inputValue)){
              console.log(item.id);
              listtable.push(item)
            }
          })
        }
      } else if (this.select === '2') { // 如果选择的是电话号
        param = `按电话号"${this.inputValue}"搜索`;
        if(this.inputValue){
          this.tableData.filter((item)=>{
            if(item.phoneNumber===this.inputValue){

              listtable.push(item)
            }
          })
        }
      } else if (this.select === '3') { // 如果选择的是预约日期

        // 按预约日期搜索
        const startDate = new Date(this.dateValue[0]); // 将起始日期转换为Date对象
        const endDate = new Date(this.dateValue[1]); // 将结束日期转换为Date对象
        param = `按预约日期"${startDate}"到"${endDate}"搜索`;

        listtable = this.tableData.filter(item => {
          const itemDate = new Date(item.orderDate);
          return itemDate >= startDate && itemDate <= endDate;
        });


      } else {
        param = '搜索所有'; // 输出搜索参数
        this.cxsyyyxx();
      }
      this.tableData=listtable;
      console.log(param); // 输出搜索参数

    },
    cxsyyyxx(){
      axios.get('api/order/findAll').then(res => {
        console.log(res)
        this.tableData = res.data.data
        console.log(this.tableData.length)
      })
    },
    tchandleSearch() { // 搜索按钮点击事件
      let param = '';
      this.gridData=this.gridData1;

      let nametclisttable=[];
      let sextclisttable=[];

      if(this.tcinputValue && this.tcradio){
        this.gridData.filter((item)=>{
          if(item.name.indexOf(this.tcinputValue)!==-1){

            nametclisttable.push(item)
          }
        })
        nametclisttable.filter((item)=>{
          if(item.sex===this.tcradio){
            sextclisttable.push(item)
          }
        })
        this.gridData=sextclisttable;

      }else{
        if(this.tcinputValue){
          this.gridData.filter((item)=>{
            if(item.name.indexOf(this.tcinputValue)!==-1){
              nametclisttable.push(item)
            }
          })
          this.gridData=nametclisttable;

        }

        if(this.tcradio){

          this.gridData.filter((item)=>{
            if(item.sex===this.tcradio){
              sextclisttable.push(item)
            }
          })
          this.gridData=sextclisttable;

        }
      }



    }

  }
}
</script>

<style lang="scss">

.wrapper {
  display: flex;
  justify-content: center;
}

.block {
  /* 添加 margin，使其左右居中 */
  margin: 0 auto;
}

</style>
<style>
/* 用来设置当前页面element全局table 选中某行时的背景色*/
.el-table__body tr.current-row>td{
  background-color: #1dbe74 !important;
  color: gold;
}
.el-select .el-input {
  width: 130px;
}

</style>
<style scoped>
.search-container {
  display: flex;
}

.input-container,
.date-picker-container,
.disabled-input-container {
  display: flex;
  align-items: center;
}

.disabled-input-container .el-input__inner {
  color: #bbb;
}
</style>
<style>


.blue-dialog .el-dialog__header {
  background-color: #199dd7;
}
.blue-dialog .el-dialog__title {
  color: white;
}

</style>
